<?php
/**
 * 验证类
 */
class Validator
{
	/**
	 * @var array list of built-in validators (name=>class)
	 */
	public $builtInValidators=array(
		'required'=>'RequiredValidator',
		'length'=>'LengthValidator',
		'email'=>'EmailValidator',
		'url'=>'UrlValidator',
		'ip'=>'IpValidator',
		'date'=>'DateValidator',
		'boolean'=>'BooleanValidator',
		'int'=>'IntValidator',
		'float'=>'FloatValidator',
		'number'=>'NumberValidator',
		'among'=>'AmongValidator',	
		'match'=>'MatchValidator'
	);
	private $aIncludedValidator=array();
	private $rules=array();
	public $aError=array();
	private $skipError=true;

	function __construct($skipError=true){
		$this->skipError=$skipError;
	}

	public function setRule($attr,$rule){
		$this->rules[$attr]=$rule;
	}

	public function appendRules($rules){
		$this->rules=array_merge($this->rules,$rules);
	}

	public function setRules($rules){
		$this->rules=$rules;
	}
	
	public function validate($aData){
		if(!is_array($aData)) return '参数必须是数组';
		if($aData===array()) return '不接受空数组的验证';
		if(empty($this->rules)) return '规则数组为空，无法验证';
		foreach($aData as $key=>$value){
			if(!array_key_exists($key,$this->rules)) continue;			
			$rule=$this->rules[$key];
			$label=array_shift($rule);
			foreach($rule as $k=>$v){
				if(is_array($v)){
					$name=$k; $aParam=$v;
				}else{
					$name=$v; $aParam=array();
				}				
				if(!in_array($name,$this->aIncludedValidator)){					
					if(!array_key_exists($name,$this->builtInValidators)) continue;
					include_once PATH_CORE.'/validator/'.$this->builtInValidators[$name].'.php';
					$this->aIncludedValidator[]=$name;
				}
				$oValidator=new $this->builtInValidators[$name];
				foreach($aParam as $attr=>$param){
					$oValidator->$attr=$param;
				}
				$result=$oValidator->validate($label,$value);
				if($result===true) continue;
				$this->aError[$key]=$result;				
				if(!$this->skipError) return $this->aError;				
			}
		}
		if($this->aError===array()) return true;
		else return $this->aError;
	}

}

